package xiong.copy.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xiong.copy.domain.GenConfig;
import xiong.copy.repository.GenConfigRepository;
import xiong.copy.service.GenConfigService;

import java.io.File;


@Service
@RequiredArgsConstructor
public class GenConfigServiceImpl implements GenConfigService {
    private final GenConfigRepository genConfigRepository;

    /**
     * @apiNote  xiong
     * 获取数据库表配置
     *
     * */

    @Override
    public GenConfig find(String tableName) {


        GenConfig genConfig = genConfigRepository.findByTableName(tableName);
        //没有表就创建
        if (genConfig!=null){
         return new GenConfig(tableName);
        }
        return genConfig;
    }

    /**
     * @apiNote  xiong
     * 将表的配置加入api
     * "前端文件路径"  将传入的包名src 加入  api
     * 保存到数据中
     * */

    @Override
    public GenConfig update(String tableName, GenConfig genConfig) {

        String separator = File.separator;
        String symbol ="\\";
        String[] paths;
        if (symbol.equals(separator)){//适配windows
            paths =    genConfig.getPath().split("\\\\");
        }else {
            paths  =genConfig.getPath().split(File.separator);
        }

        //找到src  api将包添加其后
        StringBuffer api = new StringBuffer();
        for (String path : paths){
            api.append(path);
            api.append(File.separator);
            //   src\\api
            if ("src".equals(path)){
                api.append("api");
                break;
            }

        }

        //前端路径
        genConfig.setApiPath(api.toString());
        //数据库保存 genConfig
        return genConfigRepository.save(genConfig);

    }
}
